package cn.com.se.sharepictrue.business;

import android.app.Activity;
import android.app.ProgressDialog;
import android.support.v7.app.ActionBarActivity;

import com.google.gson.internal.$Gson$Types;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import cn.com.se.sharepictrue.widget.MyProgressDialog;

/**
 * Created by KIDNG on 2015/11/28.
 */
public abstract class CallBack<T> {
    public final Type type;
    private String mMsg = "加载中...";
    private WeakReference<Activity> mActivity;
    private ProgressDialog mProgressDialog;

    public CallBack() {
        type = getSuperclassTypeParameter(getClass());
    }

    public CallBack(Activity activity) {
        this();
        mActivity = new WeakReference<Activity>(activity);
    }

    public CallBack(Activity activity, String msg) {
        this(activity);
        mMsg = msg;
    }

    static Type getSuperclassTypeParameter(Class<?> subclass) {
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterizedType = (ParameterizedType) superclass;
        return $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);
    }

    public void onPreExecute() {
    }

    public void onStart() {
        if (mActivity != null) {
            Activity activity = mActivity.get();
            if (activity != null) {
                mProgressDialog = new ProgressDialog(activity);
                mProgressDialog.setMessage(mMsg);
                mProgressDialog.show();
            }
        }
    }

    public void onSuccess(T response) {
        if (mActivity != null) {
            Activity activity = mActivity.get();
            if (activity != null && mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
        }
        onResponse(response);
    }

    public void onFailure() {
        if (mActivity != null) {
            Activity activity = mActivity.get();
            if (activity != null && mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
        }
        onFail();
    }

    public abstract void onFail();

    public abstract void onResponse(T response);
}